<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Action\Workbench;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\Utils\Common;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkContact\Contract\WorkContactTagPivotContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 拉新统计-客户统计.
 * @Controller
 */
class ContactStatistics extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeService;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactContract;

    /**
     * @Inject
     * @var WorkContactTagPivotContract
     */
    protected $workContactTagPivotService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/workContact/contactStatistics", methods="GET")
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $params['corpId'] = $user['corpId'];
        $params['employeeId'] = $user['id'];
        $params['day'] = $this->request->input('day');
        // 参数验证
        $this->validated($params);

        // 客户统计
        $statistics = $this->statistics($params);
        // 客户日统计
        $dayStatistics = $this->dayStatistics($params);
        // 员工排行
        $employeeRanking = $this->employeeRanking($params);
        // 客户来源
        $contactSource = $this->contactSource($params);
        return ['statistics' => $statistics, 'dayStatistics' => $dayStatistics, 'employeeRanking' => $employeeRanking, 'contactSource' => $contactSource];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'day' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'day.required' => '日期 必传',
        ];
    }

    private function contactSource($params): array
    {
        $contactSource = [['addWay' => 0, 'addWayName' => '其他渠道', 'count' => 0], ['addWay' => 1, 'addWayName' => '扫描二维码', 'count' => 0],
            ['addWay' => 2, 'addWayName' => '搜索手机号', 'count' => 0], ['addWay' => 3, 'addWayName' => '名片分享', 'count' => 0], ['addWay' => 4, 'addWayName' => '群聊', 'count' => 0],
            ['addWay' => 5, 'addWayName' => '手机通讯录', 'count' => 0], ['addWay' => 6, 'addWayName' => '微信联系人', 'count' => 0], ['addWay' => 7, 'addWayName' => '来自微信的添加好友申请', 'count' => 0],
            ['addWay' => 8, 'addWayName' => '安装第三方应用时自动添加的客服人员', 'count' => 0], ['addWay' => 9, 'addWayName' => '搜索邮箱', 'count' => 0], ['addWay' => 201, 'addWayName' => '内部成员共享', 'count' => 0],
            ['addWay' => 202, 'addWayName' => '管理员/负责人分配', 'count' => 0], ['addWay' => 1001, 'addWayName' => '渠道活码', 'count' => 0], ['addWay' => 1002, 'addWayName' => '自动拉群', 'count' => 0],
            ['addWay' => 1003, 'addWayName' => '裂变引流', 'count' => 0], ];
        $contactSource = array_column($contactSource, null, 'addWay');
        $contacts = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeIdCreateTimeGroupByAddWay($params['employeeId'], $params['day']);
        if (! empty($contacts)) {
            foreach ($contacts as $item) {
                $contactSource[$item['addWay']]['count'] = $item['total'];
            }
        }
        $contactSource = array_values($contactSource);
        foreach ($contactSource as $k => $v) {
            if ($v['count'] === 0) {
                unset($contactSource[$k]);
            }
        }
        return array_merge($contactSource);
    }

    private function employeeRanking($params): array
    {
        $employeeRanking = $this->workContactEmployeeService->countWorkContactEmployeesByCorpIdGroupByEmployeeId((int) $params['corpId'], date('Y-m-d', strtotime('-1 day')), date('Y-m-d'));
        $employees = $this->workEmployeeService->getWorkEmployeesByCorpId($params['corpId'], ['id', 'name', 'avatar']);
        $employees = array_column($employees, null, 'id');
        foreach ($employeeRanking as &$item) {
            $item['name'] = isset($employees[$item['employeeId']]) ? $employees[$item['employeeId']]['name'] : '';
            $item['avatar'] = isset($employees[$item['employeeId']]) ? file_full_url($employees[$item['employeeId']]['avatar']) : '';
        }
        return empty($employeeRanking) ? [] : Common::arraySort($employeeRanking, 'total', 'desc');
    }

    private function dayStatistics($params): array
    {
        $adds = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeIdCreateTimeStatusGroupByCreateTime($params['employeeId'], $params['day'], 1);
        empty($adds) || $adds = array_column($adds, null, 'createTime');
        $loss = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeIdCreateTimeStatusGroupByCreateTime($params['employeeId'], $params['day'], 2);
        empty($loss) || $loss = array_column($loss, null, 'createTime');
        $day = $params['day'];
        $dayStatistics = [];
        for ($i = 0; $i < 30; ++$i) {
            $dayStatistics[$day]['day'] = $day;
            $dayStatistics[$day]['add'] = isset($adds[$day]) ? $adds[$day]['total'] : 0;
            $dayStatistics[$day]['loss'] = isset($loss[$day]) ? $loss[$day]['total'] : 0;
            $day = date('Y-m-d', strtotime($day) + 86400);
            if (strtotime($day) > strtotime(date('Y-m-d'))) {
                break;
            }
        }
        return array_values($dayStatistics);
    }

    private function statistics($params): array
    {
        $total = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeIdCreateTimeStatus($params['employeeId'], $params['day'], 0, 0);
        $add = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeIdCreateTimeStatus($params['employeeId'], $params['day'], 0, 1);
        $loss = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeIdCreateTimeStatus($params['employeeId'], $params['day'], 0, 2);
        $totalDistinct = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeIdCreateTimeStatus($params['employeeId'], $params['day'], 1, 0);
        $addDistinct = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeIdCreateTimeStatus($params['employeeId'], $params['day'], 1, 1);
        $lossDistinct = $this->workContactEmployeeService->countWorkContactEmployeesByEmployeeIdCreateTimeStatus($params['employeeId'], $params['day'], 1, 2);
        return [
            'total' => count($total),
            'add' => count($add),
            'loss' => count($loss),
            'totalDistinct' => count($totalDistinct),
            'addDistinct' => count($addDistinct),
            'lossDistinct' => count($lossDistinct),
        ];
    }
}
